package com.dh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dh.core.common.Result;
import com.dh.dao.bo.EncryBO;
import com.dh.dao.entity.UserLogin;
import com.dh.dao.mapper.UserLoginMapper;
import com.dh.dao.vo.ResponseUserInfoVo;
import com.dh.manager.service.LoginServer;
import com.dh.manager.util.JWTUtils;
import com.dh.manager.util.WxUtils;
import com.dh.service.UserLoginService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Resource
    private JWTUtils jwtUtils;
    @Resource
    private UserLoginMapper userLoginMapper;
    @Resource
    private LoginServer loginServer;
    @Override
    @ApiModelProperty("注册或者登录")
    public Result login(EncryBO encryBO) {
        String res=WxUtils.getOpenId(encryBO.getCode());
        JSONObject jsonObject = JSONObject.parseObject(res);
        Map<String, String> map = new HashMap<>();
        for (String key : jsonObject.keySet()) {
            map.put(key, String.valueOf(jsonObject.get(key)));
        }
        if (map.containsKey("error")){
            return  Result.fail(901,"请求用户信息失败");
        }
        String openId=jsonObject.getString("openid");
        String sessionKey=jsonObject.getString("session_key");
        UserLogin userLogin=userLoginMapper.selectById(openId);
        /**
         *  如果为空则自动解密，注册
         *  如果存在该用户则生成token存到数据库，redis中并返回给前端
         */
        String token;
        if(Objects.isNull(userLogin)){
            token = loginServer.createUser(encryBO, openId, sessionKey);
        }else {
            token=loginServer.updateUser(userLogin);
        }
        ResponseUserInfoVo responseUserInfoVo=loginServer.packageVo(openId,token);
        return Result.success(responseUserInfoVo);
    }
}
